<!--配送商端-销售管理-寄售补货需求订单列表-术后退回-->
<template>
  <div class="operation-return">
    <el-container class="container-box">
      <div
        class="top-info-box"
        v-loading="topLoading">
        <!-- 顶部基本信息 -->
        <div
          class="top-info-item"
          v-for="(item,index) in deliverTopInfo"
          :key="index">
          <span class="text-left">{{ item.label }}</span>
          <span v-if="item.value=== 'orderStatus'">{{ status[formdata[item.value]] }}</span>
          <span v-else>{{ formdata[item.value] }}</span>
        </div>
        <!-- <el-form-renderer :content="content" ref="form" inline label-width="110px" /> -->
        <!-- 表单信息 -->
        <Addheadcontent
          ref="ruleFormResetFields"
          :data="adddata"
          :details="formdata"
          :rules="associationrules"
          :button-off="true"
        />
      </div>

      <!-- 去退回 -->
      <div class="btn-box">
        <el-button
          :disabled="isReturnBtn"
          type="primary"
          class="add-btn"
          @click="handleDeliverGoodsDialog"
        >
          <i class="el-icon-back"/>
          去退回</el-button>
      </div>
      <!-- 产品列表 -->
      <el-editable
        class="table-box"
        :data="tableData"
        height="200"
        v-loading="tableLoading"
        :columns="deliverGoodsColumns"
        ref="deliveryTable"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="default-placeholder"
          slot-scope="scope">
          <el-editable
            class="inside-table-box"
            :data="scope.row.distributorList"
            height="400"
            :columns="handleitemColumns"
          />
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <!-- 去发货弹窗 -->
      <el-dialog
        title="选择退回产品"
        :visible.sync="handleVisible"
        width="1367px"
        class="edit-form handle-box"
      >
        <div>
          <el-container class="handle-box">
            <!-- 长码短码 -->
            <tabs
              :tabs-arr="tabArr"
              @returnIndex="handletabsHandle" />
            <!-- 扫描条码 -->
            <el-header
              height="auto"
              class="topfrom">
              <el-form
                ref="form"
                :model="handleFormData"
                label-width="75px">
                <el-form-item label="扫描条码">
                  <el-input
                    v-model="handleFormData.barcode"
                    @change="inputFun"
                    placeholder="解码信息：此处显示扫码解析出的解码信息"
                  />
                </el-form-item>
              </el-form>
            </el-header>
            <!-- 产品 -->
            <el-editable
              class="hospital-edit-box handle-edit-box"
              :data="currentSelectedData"
              height="200"
              :columns="handlelistColumns"
            />
          </el-container>
          <h3>退回详情</h3>
          <!-- 退回数量 -->
          <el-editable
            class="hospital-edit-box"
            :data="itemList"
            height="200"
            :columns="handleitemColumns"
          >
            <template
              slot="default-udi"
              slot-scope="scope">
              <el-input
                v-model="itemList[scope.$index].udi"
                placeholder="请输入" />
            </template>
            <template
              slot="default-barCode"
              slot-scope="scope">
              <el-input
                v-model="itemList[scope.$index].barCode"
                placeholder="请输入" />
            </template>
            <template
              slot="default-productBatch"
              slot-scope="scope">
              <el-input
                v-model="itemList[scope.$index].productBatch"
                placeholder="请输入" />
            </template>
            <template
              slot="default-serialNumber"
              slot-scope="scope">
              <el-input
                v-model="itemList[scope.$index].serialNumber"
                placeholder="请输入" />
            </template>
            <template
              slot="default-productDate"
              slot-scope="scope">
              <el-date-picker
                v-model="itemList[scope.$index].productDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              />
            </template>
            <template
              slot="default-expDate"
              slot-scope="scope">
              <div>
                <el-date-picker
                  v-model="itemList[scope.$index].expDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                />
              </div>
            </template>
            <template
              slot="default-num"
              slot-scope="scope">
              <div>
                <el-input
                  v-model="itemList[scope.$index].num"
                  placeholder="请输入" />
              </div>
            </template>
            <template
              slot="default-action"
              slot-scope="scope">
              <!-- v-if="itemList.length === Number(scope.$index) + 1" -->
              <el-button
                v-if="itemList.length === Number(scope.$index) + 1"
                size="small"
                @click.stop="addList(scope.row)"
                type="text text-primary"
              >添加</el-button>
              <el-button
                v-if="itemList.length > 1"
                size="small"
                @click.stop="deleteList(scope.$index)"
                type="text text-primary"
              >删除</el-button>
            </template>
          </el-editable>
        </div>
        <div class="buttonBox">
          <el-button
            type="primary"
            @click="onSubmit">
            <i class="el-icon-circle-check"/>
            确定</el-button>
          <el-button @click="cancelsub">
            <i class="el-icon-circle-close"/>
            取消</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="手术类型"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
        <el-input
          v-model="operativeType"
          placeholder="请输入内容" />
        <div class="buttonBox">
          <el-button
            type="primary"
            @click="onSubmitType">
            <i class="el-icon-circle-check"/>
            确定</el-button>
          <el-button @click="cancelsubType">
            <i class="el-icon-circle-close"/>
            取消</el-button>
        </div>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import ElEditable from '@components/el-editable/index.vue'
import Addheadcontent from '@components/businesscomponents/addheadcontent'
import {
  postoperativeProduct,
  adddata,
  associationrules,
  handlelistColumns,
  handleitemColumns,
  TAB_ARR
} from './const.js'
import { isObject, cloneDeep, hasIn } from 'lodash'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
import {
  getTableById,
  returnOrderSubmit,
  needItemProduct
} from '@const/beforeSettleApi'
import { formatDate } from '@const/filter.js'
import tabs from '@components/tabs/index.vue'
export default {
  name: 'OperationReturn',
  components: { ElEditable, Addheadcontent, tabs },
  data () {
    return {
      operativeType: '',
      dialogVisible: false,
      historyList: [],
      // / 主要内容
      tabArr: TAB_ARR,
      handleitemColumns,
      // 是否弹窗
      handleVisible: false,
      // 扫码表单数据
      handleFormData: {
        barcode: ''
      },
      handlelistColumns, // 弹框产品表头
      // 填写物品详情
      itemList: [
        {
          udi: '',
          barCode: '',
          productBatch: '',
          serialNumber: '',
          productDate: '',
          expDate: '',
          num: ''
        }
      ],
      // 初始化物品详情
      itemListObj: {
        udi: '',
        barCode: '',
        productBatch: '',
        serialNumber: '',
        productDate: '',
        expDate: '',
        num: ''
      },

      adddata, // 表单字段
      formdata: {}, // 表单详情
      associationrules, // 表单验证
      isReturnBtn: true, // 是否禁用去退货按钮
      // ---------------------------------
      deliverTopInfo: [
        {
          label: '平台订单编号',
          value: 'orderCode'
        },
        {
          label: '订单状态',
          value: 'orderStatus'
        },
        {
          label: '订单提交时间',
          value: 'createdAt'
        },
        {
          label: '医疗机构',
          value: 'hospitalName'
        }
      ],
      // 列表配置信息
      tableLoading: false,
      topLoading: false,
      tableData: [], // 产品数据
      deliverGoodsColumns: postoperativeProduct, // 产品表头
      currentSelectedData: [], // 选中的产品
      // 分页配置信息
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      // 状态信息
      status: {
        0: '全部',
        1: '待确认',
        2: '待发货',
        3: '部分发货',
        4: '全部发货',
        5: '已完成',
        6: '已撤销',
        7: '待术后还回'
      },
      tabelIndex: null
    }
  },
  watch: {
    'formdata.operationType' (val, old) {
      if (val) {
        if (val === '其他') {
          this.formdata.operationType = ''
          this.dialogVisible = true
        }
      }
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    },
    orderCode () {
      return this.$route.query.orderCode
    }
  },
  mounted () {
    this.initNavButtons()
    this.getDeliverTopData()
    this.getDeliverTableList()
  },
  methods: {
    onSubmitType () {
      this.formdata.operationType = this.operativeType
      this.dialogVisible = false
    },
    cancelsubType () {
      this.operativeType = ''
      this.formdata.operationType = this.operativeType
      this.dialogVisible = false
    },
    handleClose () {
      this.operativeType = ''
      this.dialogVisible = false
    },
    ...mapMutations(['changeLayoutHandle']),
    // 长码短码
    handletabsHandle (index) {},
    // 确定添加
    onSubmit () {
      let index = 0
      let numData = null
      this.itemList.forEach(item => {
        numData += Number(item.num)
        for (let key in item) {
          if (!item[key]) {
            index++
          }
        }
      })
      if (index > 0) {
        this.$message({ type: 'warning', message: '请填写完整!' })
        return false
      } else {
        if (numData > this.currentSelectedData[0].purchaseNum) {
          this.$message({ type: 'warning', message: '退回数量不能大于采购数量' })
          return false
        } else {
          this.handleVisible = false
          this.currentSelectedData[0].distributorList = this.itemList
        }
      }
    },
    // 取消
    cancelsub () {
      this.handleVisible = false
      this.currentSelectedData[0].distributorList = this.historyList
    },
    // 添加一行
    addList (item) {
      let index = 0
      for (let key in item) {
        if (!item[key]) {
          index++
        }
      }
      if (index > 0) {
        this.$message({ type: 'warning', message: '请填写完整!' })
        return false
      }
      this.currentSelectedData[0].distributorList = this.historyList
      let obj = cloneDeep(this.itemListObj)
      this.itemList.push(obj)
    },
    deleteList (index) {
      let itemList = cloneDeep(this.itemList)
      if (itemList.length === 1) {
        return false
      }
      let arr = []
      itemList.forEach((item, i) => {
        if (index !== i) {
          arr.push(item)
        }
      })
      this.itemList = arr
    },
    // 扫码的内容
    inputFun (val) {
      // console.log('val')
    },
    // 右上角确认按钮
    handleNavBtnSubmit () {
      let params = this.$refs.ruleFormResetFields.serach()
      let formData = {
        id: this.$route.query.id,
        sickName: params.sickName,
        sickAge: params.sickAge,
        sickSex: params.sickSex,
        bedNum: params.bedNum,
        admissionNumber: params.admissionNumber,
        operationDoctor: params.operationDoctor, // 手术医生
        operationDate: params.operationDate, // 手术时间
        operationType: params.operationType, // 手术类型
        operationRoom: params.operationRoom, // 手术室
        createEnterprise: params.createEnterprise, // 生产企业
        makeInvoice: params.makeInvoice, // 开票日期
        afterServer: params.afterServer, // 售后服务
        invoiceNum: params.invoiceNum, // 发票号
        applianceWorker: params.applianceWorker, // 器械师
        address: params.address, // 地址
        connectPhone: params.connectPhone // 联系方式
      }
      formData.operationDate = formatDate(
        formData.operationDate,
        'YYYY-MM-DD HH:mm:ss'
      )
      formData.makeInvoice = formatDate(formData.makeInvoice, 'YYYY-MM-DD')
      let productData = []
      this.tableData.forEach(item => {
        let par = {
          followId: item.id,
          price: item.price,
          forms: item.distributorList
        }
        productData.push(par)
      })
      let data = {
        ...formData,
        detailForms: productData
      }
      this.$axios.post(returnOrderSubmit, data).then(res => {
        if (res.data.code === '0') {
          this.$router.go(-1)
        }
      })
    },
    // 去退回
    handleDeliverGoodsDialog () {
      this.handleVisible = true
      let list = this.currentSelectedData[0].distributorList
      if (list.length !== 0) {
        this.historyList = cloneDeep(list)
      }

      if (list.length !== 0) {
        this.itemList = list
      } else {
        this.itemList = [
          {
            udi: '',
            barCode: '',
            productBatch: '',
            serialNumber: '',
            productDate: '',
            expDate: '',
            num: ''
          }
        ]
      }
    },

    // 获取基本信息
    getDeliverTopData () {
      this.topLoading = true
      this.$axios
        .post(getTableById + '?id=' + this.$route.query.id)
        .then(res => {
          this.formdata = res.data.payload || {}
          this.$refs.ruleFormResetFields.resetFields()
        })
        .catch(e => {})
        .finally(() => {
          this.topLoading = false
        })
    },
    // 获取数据
    getDeliverTableList () {
      this.tableLoading = true
      this.$axios
        .post(needItemProduct, {
          page: this.curPage,
          pageSize: this.pageSize,
          id: this.id
        })
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          this.tableData = hasIn(data, ['payload', 'content'])
            ? data.payload.content
            : []
          this.tableData.forEach(item => {
            item.distributorList = []
          })
          this.totalElements = data.payload.totalElements
        })
        .catch(e => {})
        .finally(() => {
          this.tableLoading = false
        })
    },
    // 多选
    handleSelectionChange (val) {
      if (val.length > 1) {
        this.$refs.deliveryTable.$refs.table.clearSelection()
        this.$refs.deliveryTable.$refs.table.toggleRowSelection(val.pop())
      } else {
        this.currentSelectedData = val
      }
      if (this.currentSelectedData.length === 0) {
        this.isReturnBtn = true
      } else {
        this.isReturnBtn = false
      }
    },
    // 分页
    handleSizeChange (size) {
      this.pageSize = size
      this.getDeliverTableList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getDeliverTableList()
    },
    // 返回
    back () {
      this.$router.go(-1)
    },
    // 初始化 导航栏 按钮组
    initNavButtons () {
      const btn = {
        type: 'btn',
        arr: [
          {
            type: 'button',
            noReturn: true,
            val: '返回',
            handle: this.back
          },
          { type: 'primary', val: '确认退回', handle: this.handleNavBtnSubmit }
        ]
      }
      this.changeLayoutHandle(btn)
    }
  }
}
</script>

<style lang="less">
@import '../m-front-common/pc/assets/var.less';
@textColor: #26344c;
@grayColor: #a7b1c7;
@btnColor: #2371c5;
@white: #fff;

.operation-return {
  .top-info-box {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    .top-info-item {
      width: 25%;
      font-size: @defaultFontSize;
      color: @textColor;
      font-weight: 400;
      padding-bottom: 20px;

      .text-left {
        color: @grayColor;
        padding-right: 10px;
        width: 120px;
        text-align: right;
        display: inline-block;
      }
    }
  }

  .container-box {
    height: 100%;
    overflow: auto;
    display: flex;
    flex-direction: column;

    .btn-box {
      margin-bottom: 16px;
    }

    // .handle-box {
    //   .dialog-table-box {
    //     margin-bottom: 20px;
    //   }

    .topfrom {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      .el-form-item {
        display: inline-block;
      }

      .el-input {
        width: 297px;
      }
    }
  }

  .pagination {
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    padding-right: 0;
  }

  .buttonBox {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
  }

  h3 {
    line-height: 50px;
  }
}
</style>
